Array: Set get array of input fields in a form

  • STEPS

    Form fields

    1 We are using array name when looping the same input field or multiple inputs with same name 2 class reference is used for accessing array inputs fields 3 Id reference does not use for array elements syntax
    
                              $(referenceElement);
                          

    in html

                               
                                <input type="text" class="username" name="username[]" data-id="1">
                                <input type="text" class="username" name="username[]" data-id="2">
                                <input type="text" class="username" name="username[]" data-id="3">
    
                                <input type="text" class="email" name="email[]">
                                <input type="text" class="email" name="email[]">
                                <input type="text" class="email" name="email[]">
    
    
                          

    There are 3 inputs with same name username[] & email[]

    to access the array object of above inputs
    
                            var n=$('.username'); 
                            var e=$('.email');                        
                          
    to access each value of inputs using array index
    
                            n[0].value;   or   $('.username')[0].value;
                            n[1].value;   or   $('.username')[1].value;
                            n[2].value;   or   $('.username')[2].value;
                          
    to access using loop
    
                          $('.username').each(function(index, row){
                              //1. get value using this reference
                              var singleValue = $(this).val();
    
                              //2. get  value using object parameter
                              var singleValue = row.value;
    
                              //3. get  value using index of array
                              $('.username')[index].value;
    
                              //4. get other fields value 
                              var email = $('.email')[index].value;
    
                              //5. get other attributes 
                              var name = $(this).attr('data-id');
    
    
                              //apply class
                              $('.username').eq(index).parent().addClass('has-error');
    
                              
                             
                          });